<template>
  <div>
    <el-card style="margin:20px">
      <!--查询区域-->
      <el-row>
        <!--关键字查询-->
        <el-col :span="7" style="margin-bottom: 20px">
          <el-input placeholder="请输入内容" style="width: 300px" v-model="queryInfo.keyword">
            <el-button slot="append" icon="el-icon-search" @click="getNewsList" clearable></el-button>
          </el-input>
        </el-col>
        <!--日期查询-->
        <el-col :span="17" style="margin-bottom: 20px">
          <span style="margin-right:20px;font-size: 17px;">发布时间:</span>
          <el-date-picker
              style="margin-right:20px;"
              v-model="queryInfo.beginDate"
              type="date"
              clearable
              value-format="yyyy-MM-dd"
              :picker-options="pickerBeginDateBefore"
              placeholder="起始日期">
          </el-date-picker>
          <el-date-picker
              v-model="queryInfo.endData"
              type="date"
              clearable
              value-format="yyyy-MM-dd"
              :picker-options="pickerBeginDateBefore"
              placeholder="结束日期">
          </el-date-picker>
          <el-button type="primary" @click="getNewsList" style="margin-left: 10px;">查询</el-button>
          <el-button type="danger" @click="removeNewsList" >批量删除</el-button>
        </el-col>
      </el-row>
      <!-------->
      <el-row>
        <el-table border stripe :data="newsList" ref="newsRef">

          <el-table-column
              type="selection"
              width="55">
          </el-table-column>

          <el-table-column type="index" label="序号" width="80px" align="center">
            <template slot-scope="scope">
              <span style="margin-left: 10px">{{ (page - 1) * limit + (scope.$index + 1) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="新闻标题" prop="newsTitle">
          </el-table-column>
          <el-table-column label="新闻类别" width="100px" align="center">
            <el-tag>新闻</el-tag>
          </el-table-column>
          <el-table-column label="发布时间" sortable prop="newsTime" width="200px" align="center" :formatter='dateFormat' ></el-table-column>
          <el-table-column label="操作" width="300px" >
            <template slot-scope="scope">
              <el-tooltip class="item" effect="dark" content="编辑新闻" placement="top" style="margin: 0 10px">
                <el-button type="primary" class="el-icon-edit" circle @click="editNews(scope.row.newsId)"></el-button>
              </el-tooltip>

              <el-tooltip class="item" effect="dark" content="删除新闻" placement="top">
                <el-button type="danger" class="el-icon-delete" circle
                           @click="removeNews(scope.row.newsId)"></el-button>
              </el-tooltip>

              <el-tooltip class="item" effect="dark" content="发布新闻" placement="top">
                <el-button type="warning" icon="el-icon-star-off"
                           circle v-if="scope.row.newsStatus == 1" @click="submitNews(scope.row)"></el-button>
              </el-tooltip>

              <el-tooltip class="item" effect="dark" content="查看新闻" placement="top">
                <el-button type="success" icon="el-icon-zoom-in"
                           circle  @click="open(scope.row)">
                </el-button>
              </el-tooltip>

              <el-tooltip class="item" effect="dark" :content="scope.row.newsIstop === '0' ? '置顶新闻':'取消置顶'" placement="top">
                <el-switch
                    style="margin-left: 20px;"
                    v-model="scope.row.newsIstop"
                    active-color="#13ce66"
                    inactive-color="#ff4949"
                    active-value="1"
                    inactive-value="0"
                    @change="newsTop(scope.row)"
                >
                </el-switch>
              </el-tooltip>

            </template>
          </el-table-column>
        </el-table>
      </el-row>
      <el-row>
        <!-- 分页区域 -->
        <el-pagination
            style="margin-top: 20px"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="page"
            :page-sizes="[5, 10, 15]"
            :page-size="limit"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            background
        >
        </el-pagination>
      </el-row>


      <el-dialog
          :title="htmlTitle"
          :visible.sync="centerDialogVisible"
          width="80%"
          center>
        <div v-html="html"></div>
      </el-dialog>

    </el-card>
  </div>
</template>

<script>
export default {
  name: "List",
  mounted() {
    this.getNewsList();
  },
  data() {
    return {
      newsList: [],//新闻列表
      page: 1, //当前页
      limit: 5, //每页记录数
      total: 0, //总记录数
      queryInfo: {
        keyword: '',
        beginDate: null,
        endData: null,
      },
      /*新闻预览展示内容*/
      html: null,
      /*预览新闻表*/
      htmlTitle: null,
      /*新闻展示*/
      centerDialogVisible: false,
      /*最近时间*/
      pickerBeginDateBefore: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        }
      },
      // 选中的id
      ids: []
    }
  },
  methods: {
    //获取新闻列表
    async getNewsList() {
      let result = await this.$http.news.reqGetNewsList(this.page, this.limit, this.queryInfo)
      if (result.code === 200) {
        this.newsList = result.data.rows
        this.total = result.data.total
      } else {
        this.$message.error('新闻列表获取失败,请重新加载!')
      }
    },
    //.分页:显示数据行数的监听事件
    handleSizeChange(newSize) {
      this.limit = newSize
      this.getNewsList()
    },
    //.分页:页码改变监听事件
    handleCurrentChange(newPage) {
      this.page = newPage
      this.getNewsList()
    },
    //根据id删除新闻
    async removeNews(newsId) {
      const confrimResult = await this.$confirm('此操作将永久删除该新闻是否继续?', '删除提示', {
        confirmButtonText: '确认删除',
        cancelButtonText: '取消操作',
        type: "warning"
      }).catch(err => err)
      if (confrimResult !== "confirm") {
        return this.$message.info("删除操作已取消")
      }
      let result = await this.$http.news.reqRemoveNewsById(newsId)
      if (result.code === 200) {
        this.$message.success('删除成功')
        this.getNewsList()
      } else {
        this.$message.error(result.message)
      }
    },
    //编辑新闻
    editNews(newsId) {
      this.$router.push(`/new/addNews/${newsId}`)
    },
    //发布新闻
    async submitNews(news) {
      news.newsStatus = 0
      let result = await this.$http.news.reqEditNews(news)
      if (result.code !== 200) return this.$message.error("新闻发布失败")
      this.$message.success('发布成功')
      this.getNewsList()
    },
    open(news) {
      this.html = news.newsContent
      this.htmlTitle = news.newsTitle
      this.centerDialogVisible = true;
    },
    /**
     * 批量删除新闻
     * @returns {Promise<ElMessageComponent>}
     */
    async removeNewsList() {
      //判断是否选中
      if (this.$refs.newsRef.selection.length <= 0) {
        return this.$message.warning("请先选中新闻!")
      }

      //判断是否确认删除
      const confrimResult = await this.$confirm('此操作将永久删除该新闻是否继续?', '删除提示', {
        confirmButtonText: '确认删除',
        cancelButtonText: '取消操作',
        type: "warning"
      }).catch(err => err)
      if (confrimResult !== "confirm") {
        return this.$message.info("删除操作已取消")
      }
      //根据id数组批量删除新闻
      this.$refs.newsRef.selection.forEach(item => {
        this.ids.push(item.newsId)
      })
      let result = await this.$http.news.reqRemoveNewsArray(this.ids)
      if (result.code !== 200) return this.$message.error(result.message)
      this.$message.success("批量删除成功")
      this.ids = []
      this.getNewsList()
    },
   async newsTop(news) {
      /*编辑新闻*/
      //成功发送请求
      let result = await this.$http.news.reqEditNews(news)
      console.log(result)
      if (result.code !== 200) return this.$message.error("操作失败")
      this.$message.success("操作成功")
      this.getNewsList()
    },
    dateFormat (row, column) {
      var date = new Date(row.newsTime) //时间戳为10位需*1000，时间戳为13位的话不需乘1000
      var Y = date.getFullYear() + '-'
      var M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-'
      var D = date.getDate() + ' '
      var h = date.getHours() + ':'
      var m = date.getMinutes() + ':'
      var s = date.getSeconds()
      return Y+M+D+h+m+s
    },

  }
}
</script>

<style scoped>

</style>
